<template>
  <view class="index">
    <view class="test-title">
      {{ detail.title }}
    </view>
    <view class="test-img">
      <Image :src=detail.image></Image>
    </view>
    <view class="test-content">
      <nut-cell-group :title="detail.desc">
        <nut-cell>
          <nut-radio-group v-model="radioVal" @change="result">
            <nut-radio class="test-radio" icon-size="24" v-for="item in detail.options" :label="item.value">{{ item.title }}</nut-radio>
          </nut-radio-group>
        </nut-cell>
      </nut-cell-group>
    </view>
    <view class="test-pagination">
      <nut-button plain type="primary" @click="prevPage">上一题</nut-button>
      <nut-button class="test-pagination-num">{{ currentPage }}/{{ pageCount }}</nut-button>
      <nut-button plain type="primary" @click="nextPage">下一题</nut-button>
    </view>
    <view>
      <nut-button class="test-submit" type="success" size="large" @click="submit" v-show="showSubmit">完成答题</nut-button>
    </view>
  </view>
</template>

<script>
import Taro from '@tarojs/taro'
import './test.less'
import test from '@/static/test/test.json'

export default {
  data() {
    return {
      currentPage: 1,
      radioVal: 0,
      pageCount: 5,
      pageSize: 1,
      detail: {},
      showSubmit: false,
      answer: {},
    }
  },
  methods: {
    prevPage() {
      if (this.currentPage <= 1) {
        return
      }
      this.currentPage --
      this.getDetail()
    },
    nextPage() {
      if (this.currentPage >= this.pageCount) {
        return
      }
      if (this.radioVal == 0) {
        Taro.showToast({
          title: '请先选择答案',
          icon: 'none'
        })
        return
      }
      this.currentPage ++
      this.getDetail()
      if (this.currentPage >= this.pageCount) {
        this.showSubmit = true
      } else {
        this.showSubmit = false
      }
    },
    getDetail() {
      this.detail = test[this.currentPage - 1]
      this.pageCount = test.length
      let data = this.answer[this.detail.id] || {}
      this.radioVal = data.result || 0
    },
    submit() {
      if (this.radioVal == 0) {
        Taro.showToast({
          title: '请先选择答案',
          icon: 'none'
        })
        return
      }
      let score = 0
      for (var i in this.answer) {
        let item = this.answer[i]
        if (item.result == item.value) {
          score++
        }
      }
      Taro.navigateTo({
        url: '/pages/submit/submit?score=' + score
      })
    },
    result(val) {
      this.answer[this.detail.id] = {
        'id': this.detail.id,
        'value': this.detail.value,
        'result': val
      }
    }
  },
  mounted() {
    this.getDetail()
  }
}
</script>

<style lang="scss">
</style>
